<template>
  <div class="navbar">
    <div class="nav-container">
      <div class="nav-brand">
        <h2>🎨 数字藏品平台</h2>
      </div>
      
      <div class="nav-links" v-if="isLoggedIn">
        <router-link to="/" class="nav-link">
          <el-button text>主页</el-button>
        </router-link>
        <router-link to="/marketplace" class="nav-link">
          <el-button text>市场</el-button>
        </router-link>
        <router-link to="/mint" class="nav-link">
          <el-button text>铸造</el-button>
        </router-link>
        <router-link to="/my-collections" class="nav-link">
          <el-button text>我的藏品</el-button>
        </router-link>
      </div>

      <div class="nav-account">
        <!-- 已登录用户 -->
        <div v-if="isLoggedIn" class="user-section">
          <!-- 钱包状态指示器 -->
          <div class="wallet-status">
            <el-tag 
              v-if="user?.walletAddress" 
              :type="isWalletMatched ? 'success' : 'warning'"
              size="large"
              style="margin-right: 10px;"
            >
              <span v-if="isWalletMatched">✓ {{ formatAddress(user.walletAddress) }}</span>
              <span v-else>⚠ 钱包未连接</span>
            </el-tag>
            <el-tag v-else type="info" size="large" style="margin-right: 10px;">
              未绑定钱包
            </el-tag>
          </div>

          <!-- 用户下拉菜单 -->
          <el-dropdown @command="handleUserCommand">
            <span class="user-dropdown">
              <el-avatar :size="32" style="margin-right: 10px">
                {{ user?.nickname?.charAt(0) || user?.username?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="username">{{ user?.nickname || user?.username }}</span>
              <el-icon class="el-icon--right">
                <i class="el-icon-arrow-down"></i>
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>
                  <div style="font-size: 12px; color: #909399;">
                    @{{ user?.username }}
                  </div>
                </el-dropdown-item>
                <el-dropdown-item v-if="user?.walletAddress" disabled>
                  <div style="font-size: 11px; color: #67c23a;">
                    钱包: {{ formatAddress(user.walletAddress) }}
                  </div>
                </el-dropdown-item>
                <el-dropdown-item v-if="!user?.walletAddress" command="bindWallet">
                  <div style="color: #e6a23c;">
                    🔗 绑定钱包（必需）
                  </div>
                </el-dropdown-item>
                <el-dropdown-item v-if="user?.walletAddress && !isWalletMatched" command="connectWallet">
                  <div style="color: #f56c6c;">
                    🔌 连接绑定的钱包
                  </div>
                </el-dropdown-item>
                <el-dropdown-item divided command="profile">
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item command="logout" style="color: #f56c6c;">
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 未登录状态 -->
        <div v-else class="login-section">
          <el-button @click="$router.push('/login')" type="primary">
            登录
          </el-button>
          <el-button @click="$router.push('/register')" type="success">
            注册
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import web3Service from '../services/web3Service';
import userStore from '../store/userStore';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Navbar',
  setup() {
    const router = useRouter();
    const account = ref(null);

    // 用户状态
    const isLoggedIn = computed(() => userStore.getters.isLoggedIn());
    const user = computed(() => userStore.getters.getUser());
    
    // 检查钱包是否匹配
    const isWalletMatched = computed(() => {
      if (!user.value?.walletAddress || !account.value) return false;
      return account.value.toLowerCase() === user.value.walletAddress.toLowerCase();
    });

    const formatAddress = (address) => {
      if (!address) return '';
      return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
    };

    const handleConnect = async () => {
      try {
        const connectedAccount = await web3Service.connectWallet();
        account.value = connectedAccount;
        
        // 如果已登录且用户还没绑定钱包，提示是否绑定
        if (isLoggedIn.value && !user.value?.walletAddress) {
          try {
            await ElMessageBox.confirm(
              '检测到你还没有绑定钱包地址，是否现在绑定？',
              '绑定钱包',
              {
                confirmButtonText: '绑定',
                cancelButtonText: '暂不绑定',
                type: 'info',
              }
            );
            
            await userStore.actions.linkWallet(connectedAccount);
            ElMessage.success('钱包绑定成功！');
          } catch (error) {
            if (error !== 'cancel') {
              console.error('绑定失败:', error);
            }
          }
        } else {
          ElMessage.success('钱包连接成功!');
        }
      } catch (error) {
        ElMessage.error(error.message || '连接失败');
      }
    };

    const handleDisconnect = () => {
      web3Service.disconnect();
      account.value = null;
      ElMessage.info('已断开钱包连接');
    };

    const handleUserCommand = async (command) => {
      switch (command) {
        case 'profile':
          router.push('/profile');
          break;
        case 'bindWallet':
          router.push('/profile');
          ElMessage.info('请在个人中心绑定钱包');
          break;
        case 'connectWallet':
          // 提示用户切换到绑定的钱包
          try {
            await ElMessageBox.alert(
              `请在 MetaMask 中切换到您绑定的钱包地址：${user.value.walletAddress}`,
              '连接绑定的钱包',
              {
                confirmButtonText: '我已切换',
                type: 'warning',
              }
            );
            
            // 尝试连接钱包
            const connectedAccount = await web3Service.connectWallet();
            account.value = connectedAccount;
            
            // 验证是否是绑定的钱包
            if (connectedAccount.toLowerCase() === user.value.walletAddress.toLowerCase()) {
              ElMessage.success('钱包连接成功！');
            } else {
              ElMessage.error('连接的钱包地址与绑定地址不一致，请切换钱包');
            }
          } catch (error) {
            if (error !== 'cancel') {
              ElMessage.error(error.message || '连接失败');
            }
          }
          break;
        case 'logout':
          try {
            await ElMessageBox.confirm('确定要退出登录吗？', '退出登录', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            });
            
            userStore.actions.logout();
            web3Service.disconnect();
            account.value = null;
            ElMessage.success('已退出登录');
            router.push('/');
          } catch (error) {
            // 用户取消
          }
          break;
      }
    };

    onMounted(() => {
      account.value = web3Service.getAccount();
      
      // 调试日志
      console.log('Navbar mounted - 登录状态:', isLoggedIn.value);
      console.log('Navbar mounted - 用户信息:', user.value);
    });

    return {
      account,
      isLoggedIn,
      user,
      isWalletMatched,
      formatAddress,
      handleConnect,
      handleDisconnect,
      handleUserCommand
    };
  }
};
</script>

<style scoped>
.navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 1rem 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.nav-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-brand h2 {
  color: white;
  margin: 0;
  font-size: 1.5rem;
}

.nav-links {
  display: flex;
  gap: 1rem;
}

.nav-link {
  text-decoration: none;
}

.nav-link .el-button {
  color: white;
  font-size: 1rem;
  font-weight: 500;
}

.nav-link .el-button:hover {
  color: #ffd700;
}

.nav-account {
  display: flex;
  align-items: center;
}

.account-info {
  display: flex;
  align-items: center;
}

.user-section {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  margin-right: 8px;
  font-weight: 500;
}

.login-section {
  display: flex;
  gap: 10px;
  align-items: center;
}

.login-section .el-button {
  color: white;
}

.wallet-section {
  display: flex;
  align-items: center;
}

.wallet-status {
  display: flex;
  align-items: center;
}
</style>

